import {CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router} from "@angular/router";


import {Observable} from "rxjs/Observable";
import {CheckUserService} from "../check-user.service";
import {Injectable} from "@angular/core";

@Injectable()
export class UserAuthService implements CanActivate{

    public isCheck:boolean=false;

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {

        if(this.isCheck)
        {
            this.isCheck=false;
            return true;
        }

        return this.check.Check()
            .then(response=>{
                if(response.result){
                    return true;
                }else
                {
                    this.check.RouteUrl=state.url;
                    this.router.navigate(["login"]);
                }
            }).catch(ex=>{
                this.check.RouteUrl=state.url;
                this.router.navigate(["login"]);
                return false;
            });

    }


    constructor(private check:CheckUserService,private router:Router){}

}